﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FortuneArterial.Site
{
    public class ViewEngine
        : RazorViewEngine
    {

        public ViewEngine()
        {
            this.viewFormatsOringal = this.ViewLocationFormats;
            this.partialViewFormatsOringal = this.PartialViewLocationFormats;
        }

        public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)
        {
            var ns = controllerContext.Controller.GetType().Namespace;
            if (!ns.EndsWith("Controllers"))
            {
                var folder = ns.Substring(ns.LastIndexOf(".Controllers.") + ".Controllers.".Length).Replace(".", "/");
                this.PartialViewLocationFormats = new[]
                {
                    "~/Views/" + folder + "/{1}/{0}.cshtml"
                };
            }
            else
            {
                int length = this.partialViewFormatsOringal.Length;
                this.PartialViewLocationFormats = new string[length];
                Array.Copy(this.partialViewFormatsOringal, this.PartialViewLocationFormats, length);
            }

            return base.FindPartialView(controllerContext, partialViewName, useCache);
        }

        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            var ns = controllerContext.Controller.GetType().Namespace;
            if (!ns.EndsWith("Controllers"))
            {
                var folder = ns.Substring(ns.LastIndexOf(".Controllers.") + ".Controllers.".Length).Replace(".", "/");
                this.ViewLocationFormats = new[]
                {
                    "~/Views/" + folder + "/{1}/{0}.cshtml",
                    "~/Views/Shared/{0}.cshtml"
                };
            }
            else
            {
                int length = this.viewFormatsOringal.Length;
                this.ViewLocationFormats = new string[length];
                Array.Copy(this.viewFormatsOringal, this.ViewLocationFormats, length);
            }

            return base.FindView(controllerContext, viewName, masterName, useCache);
        }

        protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
        {
            return base.CreateView(controllerContext, viewPath, masterPath);
        }

        protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
        {
            return base.CreatePartialView(controllerContext, partialPath);
        }

        private string[] viewFormatsOringal;
        private string[] partialViewFormatsOringal;
    }
}